package com.ucombuy.search.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;

/**
 * Created by yaosheng on 2021/3/29.
 */
@Slf4j
public class CommonUtils {

    //computeIfAbsent是在JDK 1.8中新增的一个map方法，当key值在map中不存在时，使用Supplier懒加载一个方法并返回
    public static <K, V> V getorCreate(K key, Map<K, V> map, Supplier<V> factory) {
        return map.computeIfAbsent(key, k -> factory.get());
    }

    public static String stringConcat(String... args) {

        StringBuilder result = new StringBuilder();
        for (String arg : args) {
            result.append(arg);
            result.append("-");
        }
        result.deleteCharAt(result.length() - 1);
        return result.toString();
    }

    /**
     * 对MySQL的CST日期格式进行解析
     * Tue Jan 01 08:00:00 CST 2019
     */
    public static Date parseStringDate(String dateString) {

        try {
            DateFormat dateFormat = new SimpleDateFormat ("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
            return DateUtils.addHours(dateFormat.parse(dateString), -8);
        } catch (ParseException e) {
            log.error("parseStringDate error: {}", dateString);
            return null;
        }
    }
}
